#!/usr/bin/env python
import os
import sys
import django

# 设置Django环境
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'backend'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')
django.setup()

from apps.flowers.models import FlowerCategory, Flower

def fix_category_icons():
    """使用现有花卉图片作为分类图标"""
    
    print("修复分类图标...")
    
    # 获取每个分类的代表性花卉图片
    category_mappings = {
        '玫瑰花': '红玫瑰花束',
        '玫瑰花系列': '红玫瑰花束', 
        '康乃馨': '红康乃馨花束',
        '康乃馨系列': '红康乃馨花束',
        '百合花': '白百合花束',
        '百合花系列': '白百合花束',
        '向日葵': '向日葵花束',
        '郁金香': '粉郁金香花束',
        '满天星': '满天星花束'
    }
    
    categories = FlowerCategory.objects.all()
    updated_count = 0
    
    for category in categories:
        if category.name in category_mappings:
            flower_name = category_mappings[category.name]
            try:
                flower = Flower.objects.get(name=flower_name)
                flower_image = flower.images.filter(is_main=True).first()
                
                if flower_image:
                    old_image = category.image
                    category.image = flower_image.image_url
                    category.save()
                    print(f"✓ 更新 {category.name}: {flower_name} -> {flower_image.image_url}")
                    updated_count += 1
                else:
                    print(f"⚠ 未找到 {flower_name} 的主图")
            except Flower.DoesNotExist:
                print(f"⚠ 未找到花卉: {flower_name}")
        else:
            print(f"⚠ 未配置映射: {category.name}")
    
    print(f"\n修复完成！共更新 {updated_count} 个分类图标")
    
    # 验证结果
    print("\n最终分类图标:")
    for category in FlowerCategory.objects.all():
        print(f"{category.name}: {category.image}")

if __name__ == '__main__':
    fix_category_icons()